package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author hu
 * @date 2025/3/11
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.判断前端请求地址是否包含 特殊路径 比如 /login
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri = httpServletRequest.getRequestURI();
        if (uri.contains("/login")) {
            log.info("登陆请求，放行===");
            chain.doFilter(request, response);
            return;
        }
        //2.获取请求头中的token
        String token = httpServletRequest.getHeader("token");
        //3.判断token是否存在
        if (token == null || token.isEmpty()) {
            httpServletResponse.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            Integer emdId = Integer.valueOf(id.toString());
            CurrentHolder.setCurrentId(emdId);
            log.info("当前登陆员工id{},存入threadLocal中",emdId);
        } catch (Exception e) {
            httpServletResponse.setStatus(401);
            return;
        }
        chain.doFilter(request, response);

        //清理线程,放行,访问完资源之后删除
        CurrentHolder.remove();
    }
}
